﻿using Common;
using DBUtility;
using DeliveryManage;
using DeliveryManage.Controllers;
using DeliveryManage.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace CallRobotManage.Controllers
{
    public class GoodsController : BaseController
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;
        #region 返回新闻每页数量=========================
        private int GetPageSize(int _default_size, string CookieName)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie(CookieName, "FxManage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        #region 产品列表
        public ActionResult ProductList()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("ProductList", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            this.pageSize = GetPageSize(DTRequest.GetQueryInt("pageSize", 10), "pageSize");
            this.page = DTRequest.GetQueryInt("page", 1);

            ViewData["pageSize"] = this.pageSize;
            ViewData["page"] = this.page;
            #region 搜索
            string keywords = DTRequest.GetQueryString("keywords").Trim();
            string where = "";
            if (!string.IsNullOrEmpty(keywords))
            {
                //模糊查询
                if (keywords.IndexOf("*") >= 0)//判断字符串中是否包含字符串*号
                {
                    where = string.Format(" (Name like '{0}' or Code like '{0}')", keywords.Replace("*", "%"));
                }
                else
                {
                    where = string.Format(" (Name like '%{0}%' or Code like '%{0}%')", keywords);
                }
                ViewBag.Keyword = keywords;
            }

            #endregion
            List<DeliveryManage.Model.Pro_ShopGoods> list = new List<DeliveryManage.Model.Pro_ShopGoods>();
            DeliveryManage.DAL.Pro_ShopGoods dal = new DeliveryManage.DAL.Pro_ShopGoods();
            list = dal.GetQueryList(this.pageSize, this.page, where, "SortBy asc", out this.totalCount);
            ViewBag.ProductList = list;

            //绑定页码
            string pageUrl = Utils.CombUrlTxt("/Goods/ProductList", "page={0}&pageSize={1}&keywords={2}", "__id__", pageSize.ToString(), keywords.ToString());
            ViewBag.PageInnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
            return View();
        }
        #endregion

        #region 产品编辑
        public ActionResult ProductEdit()
        {
            DeliveryManage.Model.Sys_User user = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            int _id = DTRequest.GetQueryInt("id");
            string action = DTRequest.GetQueryString("action");
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, status = true, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("ProductList", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, status = false, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.DAL.Pro_ShopGoods dal = new DeliveryManage.DAL.Pro_ShopGoods();
            DeliveryManage.Model.Pro_ShopGoods model = new DeliveryManage.Model.Pro_ShopGoods();
            if (_id > 0)
            {
                model = dal.GetModel(_id);
            }
            else
            {

                #region 随机生成商品编码
                while (true)
                {
                    model.Code = Utils.GetCheckCode(8);
                    //判断是否存在重复编码
                    if (!dal.Exists(string.Format("Code='{0}'", model.Code)))
                    {
                        break;
                    }
                }
                #endregion
            }

            ViewBag.AddOrEdit = action;

            #region 规格单位下拉选择

            ListItemCollection Statusitem = new ListItemCollection();
            var list = Common.DTEnums.EnumToList<DTEnums.EnumSpecUnit>();
            foreach (var item in list)
            {
                Statusitem.Add(new ListItem(item.Describe, item.PrameKey.ToString()));
            }
            ViewData["SpecUnitList"] = new SelectList(Statusitem, "value", "text");

            #endregion

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult ProductEdit(FormCollection collection)
        {
            try
            {
                bool result = false;
                string action = collection["AddOrEdit"];

                #region 数据安防
                if (!ChkAdminLevels("ProductList", GetAddOrEdit(action)))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "您没有执行该操作的权限，操作失败！！" });
                }; //检查权限
                DeliveryManage.DAL.Pro_ShopGoods dal = new DeliveryManage.DAL.Pro_ShopGoods();
                if ((action == "edit" && collection["id"] == "0"))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
                }
                if (string.IsNullOrEmpty(collection["Code"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请填写产品编码！" });
                }
                if (string.IsNullOrEmpty(collection["Name"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请填写产品名称！" });
                }
                //if (string.IsNullOrEmpty(collection["Picture"]))
                //{
                //    return Json(new ReturnMsgModel { status = false, msg = "请上传产品封面图！" });
                //}
                if (string.IsNullOrEmpty(collection["CostPrice"]) || decimal.Parse(collection["CostPrice"]) < 0)
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入成本价格,必须为大于0的数字！" });
                }
                if (string.IsNullOrEmpty(collection["NormalPrice"]) || decimal.Parse(collection["NormalPrice"]) < 0)
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入市场价格,必须为大于0的数字！" });
                }
                if (bool.Parse(collection["labeType"]) == false && (string.IsNullOrEmpty(collection["CounterPrices"]) || decimal.Parse(collection["CounterPrices"]) < 0))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入正常出售价格,必须为大于0的数字！" });
                }
                else if (bool.Parse(collection["labeType"]) == true && (string.IsNullOrEmpty(collection["ActivityPrices"]) || decimal.Parse(collection["ActivityPrices"]) < 0))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入活动价格,必须为大于0的数字！" });
                }
                #endregion

                #region 数据存储
                if (action == "Add")
                {
                    //判断该编码是否存在
                    bool exist = dal.Exists(string.Format("Code='{0}'", collection["Code"]));
                    if (exist)
                    {
                        return Json(new ReturnMsgModel { status = false, msg = "该商品编码已存在！" });
                    }

                    DeliveryManage.Model.Pro_ShopGoods newmodel = new DeliveryManage.Model.Pro_ShopGoods();
                    newmodel.Code = collection["Code"];
                    newmodel.Name = collection["Name"];
                    newmodel.Picture = collection["Picture"];
                    newmodel.SortBy = int.Parse(collection["SortBy"]);
                    newmodel.CostPrice = decimal.Parse(collection["CostPrice"]);
                    newmodel.NormalPrice = decimal.Parse(collection["NormalPrice"]);
                    newmodel.Lable = bool.Parse(collection["labeType"]);
                    newmodel.CounterPrices = decimal.Parse(collection["CounterPrices"]);
                    newmodel.ActivityPrices = decimal.Parse(collection["ActivityPrices"]);
                    newmodel.Commission = decimal.Parse(collection["Commission"]);
                    newmodel.CalcSpec = int.Parse(collection["CalcSpec"]);
                    newmodel.SpecNum = int.Parse(collection["SpecNum"]);
                    newmodel.SpecUnit = collection["SpecUnit"];
                    newmodel.Stock = int.Parse(collection["Stock"]);
                    newmodel.Id = dal.Add(newmodel);
                    if (newmodel.Id > 0)
                    {
                        result = true;
                    }
                }
                else
                {
                    DeliveryManage.Model.Pro_ShopGoods model = dal.GetModel(int.Parse(collection["id"]));
                    if (model != null)
                    {
                        //判断该编码是否存在
                        bool exist = dal.Exists(string.Format("Id!={0} and Code='{1}'", model.Id, collection["Code"]));
                        if (exist)
                        {
                            return Json(new ReturnMsgModel { status = false, msg = "该商品编码已存在！" });
                        }

                        model.Code = collection["Code"];
                        model.Name = collection["Name"];
                        model.Picture = collection["Picture"];
                        model.SortBy = int.Parse(collection["SortBy"]);
                        model.CostPrice = decimal.Parse(collection["CostPrice"]);
                        model.NormalPrice = decimal.Parse(collection["NormalPrice"]);
                        model.Lable = bool.Parse(collection["labeType"]);
                        model.CounterPrices = decimal.Parse(collection["CounterPrices"]);
                        model.ActivityPrices = decimal.Parse(collection["ActivityPrices"]);
                        model.Commission = decimal.Parse(collection["Commission"]);
                        model.CalcSpec = int.Parse(collection["CalcSpec"]);
                        model.SpecNum = int.Parse(collection["SpecNum"]);
                        model.SpecUnit = collection["SpecUnit"];
                        model.Stock = int.Parse(collection["Stock"]);

                        if (dal.Update(model))
                        {
                            result = true;
                        }
                    }
                }
                #endregion

                if (result == true)
                {
                    return Json(new ReturnMsgModel { status = true, msg = "保存成功！" });
                }
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
            catch (Exception e)
            {
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" + e.Message });
            }
        }
        #endregion

        #region 删除商品
        public JsonResult DelProdouct()
        {
            string ids = DTRequest.GetFormString("id").TrimEnd(',');
            if (!ChkAdminLevels("ProductList", DTEnums.ActionEnum.Delete.ToString()))
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "您没有执行该操作的权限，操作失败！！" });
            }; //检查权限

            DeliveryManage.DAL.Pro_ShopGoods dal = new DeliveryManage.DAL.Pro_ShopGoods();

            if (!string.IsNullOrEmpty(ids))
            {
                string[] id = ids.Split(',');
                for (int i = 0; i < id.Length; i++)
                {
                    int ProId = int.Parse(id[i]);

                    //删除该商品
                    dal.Delete(ProId);
                }
            }

            return Json(new ReturnMsgModel { code = 200, msg = "删除成功！" });
        }
        #endregion

        #region 是否上架商品
        [HttpPost]
        public ActionResult IsShowProdouct(int id)
        {
            if (!ChkAdminLevels("ProductList", DTEnums.ActionEnum.Edit.ToString()))
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "您没有执行该操作的权限，操作失败！！" });
            }; //检查权限
            int _id = id;
            DeliveryManage.DAL.Pro_ShopGoods dal = new DeliveryManage.DAL.Pro_ShopGoods();
            DeliveryManage.Model.Pro_ShopGoods model = new DeliveryManage.Model.Pro_ShopGoods();
            if (_id > 0)
                model = dal.GetModel(_id);
            string msg = "";
            if (model.IsShow == false)
            {
                model.IsShow = true;
                msg = "该商品已上架成功！";
            }
            else if (model.IsShow == true)
            {
                model.IsShow = false;
                msg = "该商品已被下架！";
            }
            dal.Update(model);
            return Json(new ReturnMsgModel { code = 200, msg = msg });
        }
        #endregion

        #region 根据ID获取套餐商品详情
        /// <summary>
        /// /获取产品详细信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetGoodsDetail(int GoodsId)
        {
            try
            {
                DeliveryManage.DAL.Pro_ShopGoods dal = new DeliveryManage.DAL.Pro_ShopGoods();
                DeliveryManage.Model.Pro_ShopGoods model = dal.GetModel(GoodsId);
                if (model != null)
                {
                    return Json(new ReturnMsgModel { status = true, code = 200, msg = "获取成功!", data = model });
                }
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "暂无相关信息!" });
            }
            catch (Exception e)
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "暂无相关信息!"+ e.Message });
            }
        }
        #endregion

    }
}
